
package com.scalar.chiptrack.operations.lotshipping.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.LotView;
import com.scalar.chiptrack.operations.lotshipping.dao.LotShippingDAO;
import com.scalar.chiptrack.operations.lotshipping.forms.LotShippingInfoForm;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.Mailer;


public final class LotShippingInfoAction extends ChipTrackAction {
    
    public ActionForward execute (ActionMapping mapping,
                              ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response) 
                              throws Exception {
                                  
        String retval = "failure";
        HashMap errors = new HashMap();
        HttpSession session = request.getSession();
        String action = request.getParameter ("action");
        LotShippingInfoForm lotShippingInfoForm = (LotShippingInfoForm) form;    
    
        if ("loadVendorLocations".equalsIgnoreCase (action)) {
            try {
                ArrayList vendorLocationList = VendorDAO.getSelectedLocations (lotShippingInfoForm.getNextProcessStepId());
                request.setAttribute ("vendorLocationList", vendorLocationList);
                
                retval = "success";
            }
            catch (ScalarException se) {
                // Database exceptions
                errors.put ("Could not Load Vendor Location List from Database for this Process Step", null);
                request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
            }
        }
        
        
        if ("submit".equalsIgnoreCase (action)) {
            
            // Save the information into Lot_Shipping_Instructions Table
            int locationId = lotShippingInfoForm.getLocationId();
            int nextProcessStepId = lotShippingInfoForm.getNextProcessStepId();
            String processTimeType = lotShippingInfoForm.getProcessTimeType();
            
            LotView lview = (LotView) session.getAttribute (SessionKeys.LOT_VIEW);
            if (lview == null) {
                errors.put ("Could not find Lot information", null);
                request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
            }
            else {
                try {
                    LotShippingDAO.saveLotShippingInstructions (lview.getLotID(), lview.getDateIn(), nextProcessStepId, locationId, processTimeType);
                    retval = "success";
                }
                catch (ScalarException se) {
                    // Database Exceptions
                    errors.put ("Could not save Lot Shipping Instructions", null);
                    request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
                }
            }
            
            if (retval.equalsIgnoreCase("success") == false) {
                return (mapping.findForward (retval));
            }
            
            // Send lot shipping instructions mail to Vendor
            Address vendorAddress = null;
            String locationName = null;
            try {
                vendorAddress = VendorDAO.getVendorAddress (locationId);
                locationName = VendorDAO.getVendorLocationName (locationId);
                if (locationName == null) locationName = "";
            }
            catch (ScalarException se) {
                errors.put ("Could not locate Vendor address for this Location", null);
                request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
            }

            if (vendorAddress == null) {
                errors.put ("Could not locate Vendor address for this Location", null);
                request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
            }
            else {
                String to = vendorAddress.getEmail();
                String from = ConfigManager.getSysAdminEmail();

                String subject = "Lot Shipping Instructions for Lot Number: " + lview.getLotNumber();
                String message = formatMessage (lview, locationName, lotShippingInfoForm);
                try {
                    Mailer.send (from, to, subject, message, Mailer.CONTENT_TYPE_HTML);

                    HashMap info = new HashMap();
                    info.put ("Lot Shipping Instructions Information is saved into database and the message is sent to <b>" + to + "</b>", null);
                    request.setAttribute (SessionKeys.INFO_MESSAGES, info);

                    String returnPage = (String) session.getAttribute ("LOTVIEW_RETURN_PAGE");
                    if (returnPage != null) {
                        session.removeAttribute ("LOTVIEW_RETURN_PAGE");
                        request.setAttribute ("comingFrom", "LotShippingAction");
                        return (new ActionForward (returnPage));
                    }
                    
                    return (mapping.findForward ("lotShipping"));
                }
                catch (Exception e) {
                    errors.put ("Error sending mail to the vendor <b>(E-mail: " + to + ")</b>", null);
                    request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
                }
            }
        }
               
        return (mapping.findForward (retval));
    }
    
    
    private String formatMessage (LotView lview, String locationName, LotShippingInfoForm lotShippingInfoForm) {
        
        StringBuffer buf = new StringBuffer();
        
        buf.append ("<table border='0' width='100%' align=right>\n");
        buf.append ("<th colspan='4'><h2>Lot Shipping Instructions</h2></th>\n");
        buf.append ("<tr><td width='20%'><b>Lot Number</b></td>\n");
        buf.append ("<td width='40%'>" + lview.getLotNumber() + "</td>\n");
        buf.append ("<td width='20%'><b>Product Name</b></td>\n");
        buf.append ("<td width='20%'>" + lview.getPartNumber() + "</td>\n");
        buf.append ("</tr><tr><td width='20%'><b>Current Process</b></td>\n");
        buf.append ("<td width='40%'>" + lview.getCurrentProcess() + "</td>\n");
        buf.append ("<td width='20%'><b>Date Code</b></td>\n");
        buf.append ("<td width='20%'>" + lview.getDateCode() + "</td>\n");
        buf.append ("</tr><tr><td width='20%'><b>Vendor & Location</b></td>\n");
        buf.append ("<td width='40%'>" + lview.getVendorLocationName() + "</td>\n");
        buf.append ("<td width='20%'><b>Status</b></td>\n");
        buf.append ("<td width='20%'>" + lview.getStatus() + "</td>\n");
        buf.append ("</tr><tr><td width='20%'><b>Date In</b></td>\n");
        buf.append ("<td width='40%'>" + lview.getDateIn() + "</td>\n");
        buf.append ("<td width='20%'><b>Quantity In</b></td>\n");
        buf.append ("<td width='20%'>" + lview.getQuantityIn() + "</td>\n");
        buf.append ("</tr><tr><td width='20%'><b>Date Out</b></td>\n");
        buf.append ("<td width='40%'>" + lview.getDateOut() + "</td>\n");
        buf.append ("<td width='20%'><b>Quantity Out</b></td>\n");
        buf.append ("<td width='20%'>" + lview.getQuantityOut() + "</td>\n");
        buf.append ("</tr><tr><td width='20%'><b>Current Yield</b></td>\n");
        buf.append ("<td width='40%'>" + lview.getCurrentYield() + "</td>\n");
        buf.append ("<td width='20%'>&nbsp;</td>\n");
	buf.append ("<td width='20%'>&nbsp;</td>\n");
        buf.append ("</tr><tr><td colspan='4'>&nbsp;</td></tr>\n");
	buf.append ("<tr><td width='20%'><b>Vendor Location:</b></td>\n");
        buf.append ("<td width='40%'>" + locationName + "</td>\n");
        buf.append ("<td width='20%'><b>Process Time:</b></td>\n");
	buf.append ("<td width='20%'>" + lotShippingInfoForm.getProcessTimeType() + "</td>\n");
        buf.append ("</tr></table>\n");

        return buf.toString();
    }
}
